package com.roadjava.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.roadjava.rbac.bean.entity.LinkUserRoleDO;
import com.roadjava.rbac.mapper.LinkUserRoleMapper;
import com.roadjava.rbac.service.LinkUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 针对表【link_user_role(用户和角色关联表)】的数据库操作Service实现

 */
@Service
public class LinkUserRoleServiceImpl extends ServiceImpl<LinkUserRoleMapper, LinkUserRoleDO>
        implements LinkUserRoleService{

    @Override
    public List<Long> listRoleIdByUserId(Long userId) {
        LambdaQueryWrapper<LinkUserRoleDO> lqw = Wrappers.<LinkUserRoleDO>lambdaQuery()
                .eq(LinkUserRoleDO::getUserId, userId);
        List<LinkUserRoleDO> list = list(lqw);
        return list.stream().map(LinkUserRoleDO::getRoleId).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByRoleId(Long roleId) {
        LambdaQueryWrapper< LinkUserRoleDO> lqw = Wrappers.<LinkUserRoleDO>lambdaQuery()
                .eq(LinkUserRoleDO::getRoleId, roleId);
        int count = (int) count(lqw);
        // 使用 count 方法统计符合条件的记录数量
        if (count > 0) {
            // 如果找到了关联记录，则不删除，抛出异常或返回提示信息
            throw new IllegalStateException("存在与该角色关联的记录，无法删除");
            // 或者你可以返回某种状态来表示无法删除
        }
        remove(lqw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByUserId(Long userId) {
        LambdaQueryWrapper<LinkUserRoleDO> lqw = Wrappers.<LinkUserRoleDO>lambdaQuery()
                .eq(LinkUserRoleDO::getUserId, userId);
        remove(lqw);
    }
}




